package cn.k7g.alloy.core.objectmapper;

import cn.k7g.alloy.annotation.AlloyContent;
import cn.k7g.alloy.annotation.CodeLabelEnum;
import cn.k7g.alloy.annotation.ExpandFlag;
import cn.k7g.alloy.annotation.TimeExtra;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 对注解的支持
 * @author victor-wu
 * @date 2022年1月6日 11点16分
 */
public class AlloyAnnotationIntrospector extends AnnotationIntrospector {

    @Autowired
    private BeanFactory beanFactory;

    @Override
    public Version version() {
        return null;
    }

    @Override
    public Object findSerializer(Annotated am) {
        if (am.hasAnnotation(CodeLabelEnum.class)) {
            return new CodeLabelEnumSerializer(am.getAnnotation(CodeLabelEnum.class));
        }
        if (am.hasAnnotation(TimeExtra.class)) {
            return new TimeExtraSerializer(am.getAnnotation(TimeExtra.class));
        }
        if (am.hasAnnotation(ExpandFlag.class)) {
            return new ExpandFlagEnumSerializer(am.getAnnotation(ExpandFlag.class));
        }
        if (am.hasAnnotation(AlloyContent.class)) {
            return beanFactory.getBean(AlloyContentSerializer.class, am.getAnnotation(AlloyContent.class));
        }
        return super.findSerializer(am);
    }

    @Override
    public Object findDeserializer(Annotated am) {
        if (am.hasAnnotation(AlloyContent.class)) {
            Class dataType;
            if (am instanceof AnnotatedMethod) {
                dataType = ((AnnotatedMethod) am).getRawParameterType(0);
            } else if (am instanceof AnnotatedField) {
                dataType = am.getRawType();
            } else {
                throw new RuntimeException("无法获取到 dataType 请提交反馈");
            }
            return beanFactory.getBean(AlloyContentDeserializer.class, am.getAnnotation(AlloyContent.class), dataType);
        }
        return super.findDeserializer(am);
    }
}
